const conn = require('../config/datasql');

/** 栏目列表 */
const getType = (req, res) => {
  let sql = `select*from type where 1 = 1`;
  conn(sql, (err, result) => {
    if (err) {
      res.send({ code: 503, msg: '服务器目前异常!请稍后重试!' });
    } else {
      if (result.length) {
        res.send({ code: 1, list: [...result] });
      } else {
        res.send({ code: 0, msg: '查询失败,请重试!' });
      }
    }
  });
};

/** 删除栏目  */
const delType = (req, res) => {
  let sql = `delete from type where typeId = ${req.body.typeId}`;
  conn(sql, (err, result) => {
    if (err) {
      res.send({ code: 503, msg: '服务器目前异常!请稍后重试!' });
    } else {
      if (result.affectedRows == 1) {
        res.send({ code: 1, msg: '删除成功' });
      } else {
        res.send({ code: 0, msg: '修改失败,可能是服务器原因,期待您的重试' });
      }
    }
  });
};

/** 新增栏目 */
const adddType = async (req, res) => {
  let sql = `select*from type where type="${req.body.type}" `;
  conn(sql, (err, result) => {
    if (err) {
      res.send({ code: 503, msg: '服务器目前异常!请稍后重试!' });
    } else {
      if (result.length !== 0) {
        res.send({ code: 0, msg: '此栏目已存在,请重新进行添加!' });
      } else {
        let addsql = 'insert into type set ?';
        conn(
          addsql,
          (e, r) => {
            if (e) {
              res.send({ code: 503, msg: '服务器目前异常!请稍后重试!' });
            } else {
              if (r.affectedRows == 1) {
                res.send({ code: 1, msg: '新增成功！' });
              } else {
                res.send({ code: 0, msg: '新增失败,请稍后重试!' });
              }
            }
          },
          req.body
        );
      }
    }
  });
};

module.exports = {
  getType,
  delType,
  adddType,
};
